package com.example.skillcinema.ui.screens.main.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.example.skillcinema.adapters.FilmPagingSource
import com.example.skillcinema.db.displaymodels.FilmDisplayModel
import com.example.skillcinema.db.repositories.BaseRepository.Companion.PREVIEW_ITEMS_COUNT
import com.example.skillcinema.db.repositories.FilmRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import jakarta.inject.Inject
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

@HiltViewModel
class StaffFilmographyViewModel @Inject() constructor(val repository: FilmRepository) :
    ViewModel() {
    private var _staffFilmographyKeyStateFlow: MutableStateFlow<List<String>> =
        MutableStateFlow(listOf())
    var staffFilmographyKeyFlow = _staffFilmographyKeyStateFlow.asStateFlow()
    private val currentKey = MutableStateFlow("")
    val filmPaged: Flow<PagingData<FilmDisplayModel>> = currentKey.flatMapLatest { k ->
        Pager(
            config = PagingConfig(PREVIEW_ITEMS_COUNT),
            pagingSourceFactory = {
                FilmPagingSource { page ->
                    getFilmData(
                        page,
                        k
                    )
                }
            }).flow.cachedIn(viewModelScope)
    }
    private var _loadingStateFlow: MutableStateFlow<Boolean> = MutableStateFlow(false)
    val loadingFlow = _loadingStateFlow.asStateFlow()
    var id: Int = 0
    fun loadData() {
        viewModelScope.launch {
            _staffFilmographyKeyStateFlow.value = repository.getStaffFilmographyKeys(id)
            _loadingStateFlow.value = true
        }
    }

    fun setCurrentKey(key: String) {
        currentKey.value = key
    }

    private suspend fun getFilmData(page: Int, key: String): List<FilmDisplayModel> {
        return repository.getStaffFilmography(id, page, key)
    }
}